package main

import (
	"context"
	amqp "github.com/rabbitmq/amqp091-go"
	"time"
)

func main() {
	// 1. 建立连接
	conn, _ := amqp.Dial("amqp://guest:guest@129.211.6.176:5672/")
	defer conn.Close()
	// 2. 获取信道
	channel, _ := conn.Channel()
	defer channel.Close()
	// 3. 声明队列
	queue, _ := channel.QueueDeclare(
		"hello",
		false,
		false,
		false,
		false,
		nil,
	)
	// 4. 获取上下文
	ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelFunc()
	// 5. 发送消息
	body := "hello go-rabbitmq"
	err := channel.PublishWithContext(
		ctx,
		"",
		queue.Name, // routing key
		false,      // mandatory
		false,      // immediate
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        []byte(body),
		},
	)
	if err != nil {
		panic(err)
	}
}
